﻿using System;

using SharpBase.Web;

namespace SharpSNS.Auth
{
    /// <summary>
    /// Directly wraps the ScreenName OpenAuth API
    /// </summary>
    internal class Wrapper
    {
        /// <summary>
        /// Invokes the /clientLogin method on the OpenAuth API
        /// </summary>
        /// <param name="devId">Developer key</param>
        /// <param name="loginId">Login Id</param>
        /// <param name="pwd">Password</param>
        /// <returns>Returns a byte array representing the response</returns>
        public static byte[] clientLogin(string devId, string loginId, string pwd)
        {
            return clientLogin(devId, loginId, pwd, "SharpSNS", "1");
        }

        /// <summary>
        /// Invokes the /clientLogin method on the OpenAuth API
        /// </summary>
        /// <param name="devId">Developer key</param>
        /// <param name="loginId">Login Id</param>
        /// <param name="pwd">Password</param>
        /// <param name="clientName">Name of the client making the request</param>
        /// <param name="clientVersion">Version of the client making the request</param>
        /// <returns>Returns a byte array representing the response</returns>
        public static byte[] clientLogin(string devId, string loginId, string pwd, string clientName, string clientVersion)
        {
            WebForm submitForm = new WebForm("https://api.screenname.aol.com/auth/clientLogin?f=xml");
            submitForm.AddFormParameter("devId", devId);
            submitForm.AddFormParameter("s", loginId);
            submitForm.AddFormParameter("pwd", pwd);
            submitForm.AddFormParameter("clientVersion", clientVersion);
            submitForm.AddFormParameter("clientName", clientName);

            return Web.PostForm(submitForm);
        }

        public static byte[] startOSCARSession(string authToken, string devKey, long timeStamp, string sessionKey)
        {
            WebForm oscarForm = new WebForm("http://api.oscar.aol.com/aim/startOSCARSession");
            oscarForm.AddFormParameter("a", authToken);
            oscarForm.AddFormParameter("clientName", "SharpSNS");
            oscarForm.AddFormParameter("clientVersion", "1");
            oscarForm.AddFormParameter("f", "xml");
            oscarForm.AddFormParameter("k", devKey);
            oscarForm.AddFormParameter("ts", timeStamp.ToString());
            oscarForm.AddFormParameter("useTLS", "0");

            string sbs = RequestSigning.GenerateSignatureBaseString("GET", oscarForm);
            Console.WriteLine("SBS = \"{0}\"", sbs);
            string signature = RequestSigning.HMACSHA256Base64(sessionKey, sbs);
            oscarForm.AddFormParameter("sig_sha256", signature);
            Console.WriteLine("RequestString={0}", oscarForm.GetWebFormString());
            return Web.GetForm(oscarForm);
        }
    }
}
